//
//  WXViewController.m
//  WFCoretext
//
//  Created by 阿虎 on 14/10/28.
//  Copyright (c) 2014年 tigerwf. All rights reserved.
//

#import "WXViewController.h"
#import "YMTableViewCell.h"
#import "ContantHead.h"
#import "YMShowImageView.h"
#import "YMTextData.h"
#import "YMReplyInputView.h"
#import "WFReplyBody.h"
#import "WFMessageBody.h"
#import "WFPopView.h"
#import "WFActionSheet.h"
#import "LinliViewController.h"
#import "MainViewController.h"
#import "YoukeViewController.h"
#import "MJRefresh.h"

#define dataCount 10
#define kLocationToBottom 20

@interface WXViewController ()<UITableViewDataSource,UITableViewDelegate,cellDelegate,InputDelegate,UIActionSheetDelegate>
{
    NSMutableArray *_imageDataSource;
    
    NSMutableArray *_contentDataSource;//模拟接口给的数据
    
    NSMutableArray *_tableDataSource;//tableview数据源
    
    NSMutableArray *_shuoshuoDatasSource;//说说数据源
    
    UITableView *mainTable;
    
    UIView *popView;
    
    YMReplyInputView *replyView ;
    
    NSInteger _replyIndex;
    
    
}
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic,strong) WFPopView *operationView;
@property (nonatomic,strong) NSIndexPath *selectedIndexPath;
@property (nonatomic, strong) NetworkManager *networkManager;
@end

@implementation WXViewController


#pragma mark - 数据源
- (void)configData{
    
    _tableDataSource = [[NSMutableArray alloc] init];
    _contentDataSource = [[NSMutableArray alloc] init];
    _replyIndex = -1;//代表是直接评论
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController setNavigationBarHidden:YES];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    backBtn.frame = CGRectMake(0, -20, self.view.frame.size.width, 84);
    
    UILabel *tileLabel = [[UILabel alloc]initWithFrame:CGRectMake(125, 31, 88, 35)];
    
    UserInfo *user = [UserInfo instance];
    
    UIImageView *beijing =  [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
    beijing.image = [UIImage imageNamed:@"beijing2.png"];
    [self.view addSubview:beijing];
    
    UIButton *backBtn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.view addSubview:backBtn1];
    backBtn.backgroundColor = [UIColor clearColor];
    [self.view addSubview:backBtn];
    [tileLabel setText:@"邻里小圈"];
    [tileLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
    [tileLabel setTextColor:[UIColor colorWithRed:217/255.0 green:185/255.0 blue:122/255.0 alpha:1.0]];
    //[tileLabel setbackg];
    [self.view addSubview:tileLabel];
    
    UIButton *fanhui = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [fanhui setBackgroundImage:[UIImage imageNamed:@"top_back.png"] forState:UIControlStateNormal];
    fanhui.frame = CGRectMake(7, 42, 10, 14);
    [self.view addSubview:fanhui];
    
    UIButton *fanhui2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [fanhui2 setTitle:[NSString stringWithFormat:@"返回"] forState:UIControlStateNormal];
    fanhui2.frame = CGRectMake(20, 38, 34, 22);
    [fanhui2 setTitleColor:[UIColor colorWithRed:217/255.0 green:185/255.0 blue:122/255.0 alpha:1.0]forState:UIControlStateNormal];
    [self.view addSubview:fanhui2];
    UIButton *fanhui3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    fanhui3.frame = CGRectMake(0, -20, 80, 84);
    [self.view addSubview:fanhui3];
    
    if((user.info != nil && [user.info objectForKey:@"c2"] && [[user.info objectForKey:@"c2"] isEqualToString:@"1"]) || [[[user.info objectForKey:@"isofficer"] stringValue]isEqualToString:@"1"]){
        UIButton *addShuoshuo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [addShuoshuo setBackgroundImage:[UIImage imageNamed:@"xiangji.png"] forState:UIControlStateNormal];
        addShuoshuo.frame = CGRectMake(285, 38, 23, 23);
        [self.view addSubview:addShuoshuo];
        [addShuoshuo addTarget:self action:@selector(addShuoshuo) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [fanhui3 addTarget:self action:@selector(backToPre) forControlEvents:UIControlEventTouchUpInside];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    if(xiaoqu_id == nil){
        xiaoqu_id = @"8";
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           xiaoqu_id,@"xiaoqu_id", nil];
    [self.networkManager requestWithMethod2:getShoushuoByXiaoqu parameter:param delegate:self];
    [self configData];
    [self.HUD show:YES];
    
}


- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    
    if (methodId == getShoushuoByXiaoqu) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            
            if([result isEqualToString:@"000"]){
                NSArray *results = [data objectForKeyOrNil:@"shuoshuoList"];
                
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    WFMessageBody *messBody7;
                    NSString *image1Str;
                    
                    for( int i=0; i<[results count]; i++){
                        NSLog(@"%i-%@", i, [results objectAtIndex:i]);//
                        NSDictionary* dic = [results objectAtIndex:i] ;
                        NSLog(@"the content is %@",[dic objectForKey:@"content"]);
                        messBody7 = [[WFMessageBody alloc] init];
                        messBody7.ssId = [dic objectForKey:@"id"];
                        messBody7.posterContent =
                        [[dic objectForKey:@"content"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        if([dic valueForKey:@"touxiang"] != nil){
                            image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,[dic valueForKey:@"touxiang"]];
                        } else {
                            image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,@"home_photo.png"];
                        }
                        
                        messBody7.posterImgstr =image1Str;//头像
                        
                        if([dic valueForKey:@"pics"] != nil && ![[dic valueForKey:@"pics"] isEqualToString:@""]){
                            NSArray *picsArray = [[dic valueForKey:@"pics"] componentsSeparatedByString:@","];
                            NSString *image2Str =@"";
                            for(int j=0;j<[picsArray count];j++){
                                image2Str = [NSString stringWithFormat:@"%@,%@%@",image2Str,SERVER_PATH,[picsArray objectAtIndex:j]];
                            }
                            messBody7.posterPostImage = @[image2Str];
                            
                        }
                        
                        NSString *nickname = [dic objectForKey:@"nickname"] ;
                        
                        if(nickname == nil || [@"" isEqualToString:nickname]){
                            messBody7.posterName = [dic objectForKey:@"username"];
                        } else {
                            messBody7.posterName = [[dic objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        }
                        UserInfo *user = [UserInfo instance];
                        NSString * nicknameNow = [[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        
                        if(nicknameNow == nil || [@"" isEqualToString:nicknameNow]){
                            nicknameNow =[user.info objectForKey:@"username"];
                        } else {
                            nicknameNow =[[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        }
                        if([nicknameNow isEqualToString:messBody7.posterName]){
                           
                           messBody7.isSelf = YES;
                        } else {
                           messBody7.isSelf = NO;
                        }
                        messBody7.fabuDate = [dic objectForKey:@"fabuDate"];
                        messBody7.posterFavour = [NSMutableArray arrayWithObjects: [dic objectForKey:@"zans"],nil];
                        
                        if([dic objectForKey:@"zans"] == nil || [[dic objectForKey:@"zans"] isEqualToString:@""] ||(nicknameNow!=nil && [[dic objectForKey:@"zans" ] rangeOfString:nicknameNow].location == NSNotFound)){
                            messBody7.isFavour = NO;
                        } else {
                            messBody7.isFavour = YES;
                        }
                        NSArray *pinglunList = [dic objectForKeyOrNil:@"pinglunList"];
                        if (![pinglunList isKindOfClass:[NSNull class]] && [pinglunList count] > 0) {
                    
                            NSMutableArray *muArray = [NSMutableArray arrayWithCapacity:3];
                            for( int i=0; i<[pinglunList count]; i++){
                                NSDictionary* pinglun = [pinglunList objectAtIndex:i] ;
                                WFReplyBody *body1 = [[WFReplyBody alloc] init];
                                body1.replyUserId =[pinglun objectForKey:@"fromId"];
                                body1.repliedUserId =[pinglun objectForKey:@"toId"];
                                body1.replyUser = [pinglun objectForKey:@"fromName"];
                                body1.repliedUser = [pinglun objectForKey:@"toName"];
                                body1.replyInfo = [pinglun objectForKey:@"content"];
                                body1.replyId =[pinglun objectForKey:@"id"];
                                
                                [muArray addObject:body1];
                            }
                            messBody7.posterReplies = muArray;
                        } else {
                            messBody7.posterReplies = [NSMutableArray arrayWithObjects:nil];
                        }
                        
                        
                        [_contentDataSource addObject:messBody7];
                    }
                    
                    [self initTableview];
                    
                    [self loadTextData];
                    
                }
                
                
            } else if([result isEqualToString:@"001"]){
                NSString * resultinfo = [data objectForKeyOrNil:@"resultinfo"];
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                                message:[resultinfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
//                                                               delegate:nil
//                                                      cancelButtonTitle:@"确定"
//                                                      otherButtonTitles:nil];
//                [alert show];
                BTToast([resultinfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
            }
        }
        
    }
    [self.HUD hide:YES];
}



#pragma mark -加载数据
- (void)loadTextData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableArray * ymDataArray =[[NSMutableArray alloc]init];
        
        for (int i = 0 ; i < _contentDataSource.count; i ++) {
            
            WFMessageBody *messBody = [_contentDataSource objectAtIndex:i];
            
            YMTextData *ymData = [[YMTextData alloc] init ];
            ymData.messageBody = messBody;
            
            [ymDataArray addObject:ymData];
            
        }
        [self calculateHeight:ymDataArray];
        
    });
}



#pragma mark - 计算高度
- (void)calculateHeight:(NSMutableArray *)dataArray{
    
    NSDate* tmpStartData = [NSDate date];
    for (YMTextData *ymData in dataArray) {
        ymData.shuoshuoHeight = [ymData calculateShuoshuoHeightWithWidth:self.view.frame.size.width withUnFoldState:NO];//折叠
        ymData.unFoldShuoHeight = [ymData calculateShuoshuoHeightWithWidth:self.view.frame.size.width withUnFoldState:YES];//展开
        ymData.replyHeight = [ymData calculateReplyHeightWithWidth:self.view.frame.size.width];
        ymData.favourHeight = [ymData calculateFavourHeightWithWidth:self.view.frame.size.width];
        [_tableDataSource addObject:ymData];
    }
    
    double deltaTime = [[NSDate date] timeIntervalSinceDate:tmpStartData];
    dispatch_async(dispatch_get_main_queue(), ^{
        [mainTable reloadData];
        
    });
}




- (void)backToPre{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addShuoshuo{
    CATransition* transition = [CATransition animation];
    transition.type = kCATransitionPush;//可更改为其他方式
    transition.subtype = kCATransitionFromRight;//可更改为其他方式
    UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LinliViewController *problemVC = (LinliViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"LinliViewController"];
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    [self.navigationController pushViewController:problemVC animated:NO];
}

- (void) initTableview{
     mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height-70)];
    mainTable.backgroundColor = [UIColor clearColor];
    mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    mainTable.delegate = self;
    mainTable.dataSource = self;
    [mainTable addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.view addSubview:mainTable];
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [mainTable addHeaderWithTarget:self action:@selector(headerRereshing)];
    [mainTable headerBeginRefreshing];
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    mainTable.headerPullToRefreshText = @"下拉可以刷新了";
    mainTable.headerReleaseToRefreshText = @"松开马上刷新了";
    mainTable.headerRefreshingText = @"智慧管家正在帮你刷新中...";
    
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 1秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [mainTable reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [mainTable headerEndRefreshing];
    });
}

//**
// *  ///////////////////////////////////////////////////
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  _tableDataSource.count;
}

//table cell高度设定
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    YMTextData *ym = [_tableDataSource objectAtIndex:indexPath.row];
    BOOL unfold = ym.foldOrNot;
    return TableHeader + kLocationToBottom + ym.replyHeight + ym.showImageHeight  + kDistance + (ym.islessLimit?0:30) + (unfold?ym.shuoshuoHeight:ym.unFoldShuoHeight) + kReplyBtnDistance + ym.favourHeight + (ym.favourHeight == 0?0:kReply_FavourDistance)-33;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"ILTableViewCell";
    YMTableViewCell *cell = (YMTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell = [[YMTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.stamp = indexPath.row;
        cell.replyBtn.appendIndexPath = indexPath;
        [cell.replyBtn addTarget:self action:@selector(replyAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.delegate = self;
        [cell setYMViewWith:[_tableDataSource objectAtIndex:indexPath.row]];
  
    return cell;
}

////////////////////////////////////////////////////////////////////

#pragma mark - 按钮动画

- (void)replyAction:(YMButton *)sender{
    UserInfo *user = [UserInfo instance];
    if(user.info == nil){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请先登录帐号,游客不可评论和赞"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
//    if(!(([user.info objectForKey:@"c2"] && [[user.info objectForKey:@"c2"] isEqualToString:@"1"]) || [[[user.info objectForKey:@"isofficer"] stringValue]isEqualToString:@"1"])){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                        message:@"您暂时没有权限查看此功能"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
//        return;
//    }
    CGRect rectInTableView = [mainTable rectForRowAtIndexPath:sender.appendIndexPath];
    CGFloat origin_Y = rectInTableView.origin.y + sender.frame.origin.y;
    CGRect targetRect = CGRectMake(CGRectGetMinX(sender.frame), origin_Y, CGRectGetWidth(sender.bounds), CGRectGetHeight(sender.bounds));
    if (self.operationView.shouldShowed) {
        [self.operationView dismiss];
        return;
    }
    _selectedIndexPath = sender.appendIndexPath;
    YMTextData *ym = [_tableDataSource objectAtIndex:_selectedIndexPath.row];
    [self.operationView showAtView:mainTable rect:targetRect isFavour:ym.hasFavour];
}

- (WFPopView *)operationView {
    if (!_operationView) {
        _operationView = [WFPopView initailzerWFOperationView];
        WS(ws);
        _operationView.didSelectedOperationCompletion = ^(WFOperationType operationType) {
            switch (operationType) {
                case WFOperationTypeLike:
                    
                    [ws addLike];
                    break;
                case WFOperationTypeReply:
                    [ws replyMessage: nil];
                    break;
                default:
                    break;
            }
        };
    }
    return _operationView;
}

#pragma mark - 赞
- (void)addLike{
    UserInfo *user = [UserInfo instance];
//    if(!(([user.info objectForKey:@"c2"] && [[user.info objectForKey:@"c2"] isEqualToString:@"1"]) || [[[user.info objectForKey:@"isofficer"] stringValue]isEqualToString:@"1"])){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                        message:@"您暂时没有权限查看此功能"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
//        return;
//    }

    NSString * nickname = [[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if(nickname == nil || [@"" isEqualToString:nickname]){
        nickname = [[user.info objectForKey:@"username"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    YMTextData *ymData = (YMTextData *)[_tableDataSource objectAtIndex:_selectedIndexPath.row];

    WFMessageBody *m = ymData.messageBody;

    NSString *favourStr;
    NSArray *array;
    if(m.posterFavour != nil && [m.posterFavour count] > 0){
        favourStr = [m.posterFavour objectAtIndex:0];
        array = [favourStr componentsSeparatedByString:@","];
    } else {
        favourStr = @"";
        array = [[NSArray alloc] init];
    }

    NSMutableArray *myMutableArray = [array mutableCopy];
    if (m.isFavour == YES) {//此时该取消赞
        [myMutableArray removeObject:nickname];
        m.isFavour = NO;
    }else{
        if( myMutableArray != nil && [myMutableArray count]>0 && [[myMutableArray objectAtIndex:0] isEqualToString:@""]){
            [myMutableArray removeObject:@""];
        }
        [myMutableArray addObject:nickname];
        m.isFavour = YES;
    }
    NSLog(@"posterFavour===%@",myMutableArray);
    
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *user_id = [user.info objectForKey:@"user_id"] ;
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:user_id,@"user_id",m.ssId,@"ss_id",m.isFavour?@"YES":@"NO",@"isFavour",nil];
    [self.networkManager requestWithMethod:zanDo parameter:param delegate:self];
  
    m.posterFavour = myMutableArray;
    ymData.messageBody = m;
    //清空属性数组。否则会重复添加
    [ymData.attributedDataFavour removeAllObjects];
    ymData.favourHeight = [ymData calculateFavourHeightWithWidth:self.view.frame.size.width];
    [_tableDataSource replaceObjectAtIndex:_selectedIndexPath.row withObject:ymData];
    [mainTable reloadData];
    [self.view addSubview:replyView];
}


#pragma mark - 真の评论
- (void)replyMessage:(YMButton *)sender{
    if (replyView) {
        return;
    }
    replyView = [[YMReplyInputView alloc] initWithFrame:CGRectMake(55, self.view.frame.size.height - 44, screenWidth,44) andAboveView:self.view];
    replyView.delegate = self;
    replyView.replyTag = _selectedIndexPath.row;
    [self.view addSubview:replyView];
    
}


#pragma mark -移除评论按钮
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.operationView dismiss];
}


#pragma mark -cellDelegate
- (void)changeFoldState:(YMTextData *)ymD onCellRow:(NSInteger)cellStamp{
    [_tableDataSource replaceObjectAtIndex:cellStamp withObject:ymD];
    [mainTable reloadData];
    
}

- (void)deleteShuoshuo{
    [mainTable removeFromSuperview];
    UserInfo *user = [UserInfo instance];
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    if(xiaoqu_id == nil){
        xiaoqu_id = @"8";
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           xiaoqu_id,@"xiaoqu_id", nil];
    [self.networkManager requestWithMethod:getShoushuoByXiaoqu parameter:param delegate:self];
    [self configData];
    [self.HUD show:YES];
}

#pragma mark - 图片点击事件回调
- (void)showImageViewWithImageViews:(NSArray *)imageViews byClickWhich:(NSInteger)clickTag{
    UIView *maskview = [[UIView alloc] initWithFrame:self.view.bounds];
    maskview.backgroundColor = [UIColor blackColor];
    [self.view addSubview:maskview];
    YMShowImageView *ymImageV = [[YMShowImageView alloc] initWithFrame:self.view.bounds byClick:clickTag appendArray:imageViews];
    [ymImageV show:maskview didFinish:^(){
        [UIView animateWithDuration:0.5f animations:^{
            ymImageV.alpha = 0.0f;
            maskview.alpha = 0.0f;
            
        } completion:^(BOOL finished) {
            
            [ymImageV removeFromSuperview];
            [maskview removeFromSuperview];
        }];
        
    }];
    
}

#pragma mark - 长按评论整块区域的回调
- (void)longClickRichText:(NSInteger)index replyIndex:(NSInteger)replyIndex{
    [self.operationView dismiss];
    YMTextData *ymData = (YMTextData *)[_tableDataSource objectAtIndex:index];
    WFReplyBody *b = [ymData.messageBody.posterReplies objectAtIndex:replyIndex];
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = b.replyInfo;
    
}

#pragma mark - 点评论整块区域的回调
- (void)clickRichText:(NSInteger)index replyIndex:(NSInteger)replyIndex{
    
    [self.operationView dismiss];
    _replyIndex = replyIndex;
    YMTextData *ymData = (YMTextData *)[_tableDataSource objectAtIndex:index];
    WFReplyBody *b = [ymData.messageBody.posterReplies objectAtIndex:replyIndex];
    UserInfo *user = [UserInfo instance];
//    if(!([user.info objectForKey:@"c2"] && [[user.info objectForKey:@"c2"] isEqualToString:@"1"]) || [[user.info objectForKey:@"isofficer"] isEqualToString:@"1"]){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                        message:@"您暂时没有权限查看此功能"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
//        return;
//    }

    NSString * nickname = [[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if(nickname == nil || [@"" isEqualToString:nickname]){
        nickname =[user.info objectForKey:@"username"];
    } else {
        nickname =[[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    
    if ([b.replyUser isEqualToString:nickname]) {
        WFActionSheet *actionSheet = [[WFActionSheet alloc] initWithTitle:@"删除评论？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil, nil];
        actionSheet.actionIndex = index;
        [actionSheet showInView:self.view];
        
        
        
    }else{
        //回复
        if (replyView) {
            return;
        }
        replyView = [[YMReplyInputView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 44, screenWidth,44) andAboveView:self.view];
        replyView.delegate = self;
        replyView.lblPlaceholder.text = [NSString stringWithFormat:@"回复%@：",b.replyUser];
        replyView.replyTag = index;
        [self.view addSubview:replyView];
    }
}

#pragma mark - 评论说说回调
- (void)YMReplyInputWithReply:(NSString *)replyText appendTag:(NSInteger)inputTag{
    UserInfo *user = [UserInfo instance];
//    if(!(([user.info objectForKey:@"c2"] && [[user.info objectForKey:@"c2"] isEqualToString:@"1"])) || [[[user.info objectForKey:@"isofficer"] stringValue]isEqualToString:@"1"]){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                        message:@"您暂时没有权限查看此功能"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
//        return;
//    }

    NSString * nickname = [[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if(nickname == nil || [@"" isEqualToString:nickname]){
        nickname =[user.info objectForKey:@"username"];
    } else {
        nickname =[[user.info objectForKey:@"nickname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    NSString * ssId =@"";
    NSString * toUser =@"";
    YMTextData *ymData2 = nil;
     if (_replyIndex == -1) {
        WFReplyBody *body2 = [[WFReplyBody alloc] init];
        body2.replyUser = nickname;
        body2.repliedUser = @"";
        body2.replyInfo = replyText;
        ymData2 = (YMTextData *)[_tableDataSource objectAtIndex:inputTag];
        WFMessageBody *m2 = ymData2.messageBody;
        [m2.posterReplies addObject:body2];
        ymData2.messageBody = m2;
        ssId = m2.ssId;
        
    }else{
        ymData2 = (YMTextData *)[_tableDataSource objectAtIndex:inputTag];
        WFMessageBody *m = ymData2.messageBody;
        WFReplyBody *body = [[WFReplyBody alloc] init];
        body.replyUser = nickname;
        body.repliedUser = [(WFReplyBody *)[m.posterReplies objectAtIndex:_replyIndex] replyUser];
        body.replyInfo = replyText;
        
        [m.posterReplies addObject:body];
        ymData2.messageBody = m;
        ssId = m.ssId;
        toUser= [(WFReplyBody *)[m.posterReplies objectAtIndex:_replyIndex] replyUserId];
        
    }
    
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    
    NSString *user_id = [user.info objectForKey:@"user_id"] ;
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           user_id,@"user_id", replyText,@"reply_text",
                           ssId,@"ss_id",toUser,@"to_user",nil];
    [self.networkManager requestWithMethod:addPinglun parameter:param delegate:self];
    
    //清空属性数组。否则会重复添加
    [ymData2.completionReplySource removeAllObjects];
    [ymData2.attributedDataReply removeAllObjects];
   
    ymData2.replyHeight = [ymData2 calculateReplyHeightWithWidth:self.view.frame.size.width];
    [_tableDataSource replaceObjectAtIndex:inputTag withObject:ymData2];
    
    [mainTable reloadData];
    
    
}

- (void)destorySelf{
    [replyView removeFromSuperview];
    replyView = nil;
    _replyIndex = -1;
    
}

- (void)actionSheet:(WFActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //delete
        YMTextData *ymData = (YMTextData *)[_tableDataSource objectAtIndex:actionSheet.actionIndex];
        WFMessageBody *m = ymData.messageBody;

        UserInfo *user = [UserInfo instance];
        NSString *user_id = [user.info objectForKey:@"user_id"] ;
        
        WFReplyBody *rb =[ymData.messageBody.posterReplies objectAtIndex:_replyIndex];
        
        if (self.networkManager == nil) {
            self.networkManager = [[NetworkManager alloc] init];
        }
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               user_id,@"user_id", rb.replyId ,@"replyId",nil];
        [self.networkManager requestWithMethod:deletePinglun parameter:param delegate:self];
        
        [m.posterReplies removeObjectAtIndex:_replyIndex];
        ymData.messageBody = m;
        [ymData.completionReplySource removeAllObjects];
        [ymData.attributedDataReply removeAllObjects];
        
        ymData.replyHeight = [ymData calculateReplyHeightWithWidth:self.view.frame.size.width];
        [_tableDataSource replaceObjectAtIndex:actionSheet.actionIndex withObject:ymData];
        
        [mainTable reloadData];
        
    }else{
        
    }
    _replyIndex = -1;
}

- (void)dealloc{
    
    NSLog(@"销毁");
    
}

@end
